<script setup lang='ts'>
import { onMounted, ref, computed } from 'vue'
import { listOrders, updateOrder, deleteOrders } from '@/api/order'
import { listOrderGoods } from '@/api/orderGoods'
import { fetchGoodDetail } from '@/api/good'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores/auth'

const auth = useAuthStore()
const loading = ref(false)
const list = ref<any[]>([])
const selectedRows = ref<any[]>([])

// 查询条件与分页
const current = ref(1)
const size = ref(10)
const total = ref(0)
const status = ref<string | ''>('')
const keyword = ref('')

const statusOptions = [
  { label: '全部', value: '' },
  { label: '已创建', value: 'CREATED' },
  { label: '已支付', value: 'PAID' },
  { label: '已取消', value: 'CANCELLED' },
]

// 订单明细缓存：orderId -> { loading, items }
const detailsMap = ref<Record<string, { loading: boolean; items: any[] }>>({})

async function load() {
  if (!auth.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }
  loading.value = true
  try {
    const params: any = { current: current.value, size: size.value }
    if (status.value) params.status = status.value
    if (keyword.value) params.orderNo = keyword.value
    const res = await listOrders(params)
    const data = res?.data?.data
    const records = data?.records
    list.value = Array.isArray(records) ? records : []
    total.value = Number(data?.total || list.value.length || 0)
  } catch (e:any) {
    ElMessage.error(e?.message || '加载失败')
  } finally {
    loading.value = false
  }
}

async function loadDetails(order: any) {
  const key = String(order.id)
  if (!detailsMap.value[key]) {
    detailsMap.value[key] = { loading: true, items: [] }
  } else if (detailsMap.value[key].items.length) {
    return
  }
  detailsMap.value[key].loading = true
  try {
    const res = await listOrderGoods({ orderId: order.id, current: 1, size: 100 })
    const records = res?.data?.data?.records || []
    const items = await Promise.all(records.map(async (og: any) => {
      try {
        const gd = await fetchGoodDetail(og.goodId)
        const good = gd?.data?.data
        return { ...og, good }
      } catch {
        return { ...og, good: null }
      }
    }))
    detailsMap.value[key].items = items
  } catch (e:any) {
    ElMessage.error(e?.message || '加载订单明细失败')
  } finally {
    detailsMap.value[key].loading = false
  }
}

function onRowExpand(row: any, expanded: boolean) {
  if (expanded) loadDetails(row)
}

function formatStatus(s?: string){
  const map: Record<string,string> = { CREATED: '已创建', PAID: '已支付', CANCELLED: '已取消' }
  return map[String(s||'')] || String(s||'-')
}

async function handlePay(row: any){
  try{
    await ElMessageBox.confirm(`确认支付订单 ${row.orderNo} 吗？`, '提示', { type: 'warning' })
    await updateOrder({ id: row.id, state: 'PAID' })
    ElMessage.success('已支付')
    load()
  }catch{}
}

async function handleCancel(row: any){
  try{
    await ElMessageBox.confirm(`确认取消订单 ${row.orderNo} 吗？`, '提示', { type: 'warning' })
    await updateOrder({ id: row.id, state: 'CANCELLED' })
    ElMessage.success('已取消')
    load()
  }catch{}
}

async function handleDelete(row: any){
  try{
    await ElMessageBox.confirm(`确认删除订单 ${row.orderNo} 吗？`, '提示', { type: 'warning' })
    await deleteOrders([row.id])
    ElMessage.success('已删除')
    load()
  }catch{}
}

// 批量操作
function onSelectionChange(selection: any[]){
  selectedRows.value = selection
}

async function batchPay(){
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要支付的订单')
    return
  }
  const createdOrders = selectedRows.value.filter(r => r.state === 'CREATED')
  if (!createdOrders.length) {
    ElMessage.warning('所选订单中没有可支付的订单')
    return
  }
  try{
    await ElMessageBox.confirm(`确认支付 ${createdOrders.length} 个订单吗？`, '批量支付', { type: 'warning' })
    await Promise.all(createdOrders.map(r => updateOrder({ id: r.id, state: 'PAID' })))
    ElMessage.success(`已支付 ${createdOrders.length} 个订单`)
    selectedRows.value = []
    load()
  }catch{}
}

async function batchCancel(){
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要取消的订单')
    return
  }
  const createdOrders = selectedRows.value.filter(r => r.state === 'CREATED')
  if (!createdOrders.length) {
    ElMessage.warning('所选订单中没有可取消的订单')
    return
  }
  try{
    await ElMessageBox.confirm(`确认取消 ${createdOrders.length} 个订单吗？`, '批量取消', { type: 'warning' })
    await Promise.all(createdOrders.map(r => updateOrder({ id: r.id, state: 'CANCELLED' })))
    ElMessage.success(`已取消 ${createdOrders.length} 个订单`)
    selectedRows.value = []
    load()
  }catch{}
}

async function batchDelete(){
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的订单')
    return
  }
  try{
    await ElMessageBox.confirm(`确认删除 ${selectedRows.value.length} 个订单吗？`, '批量删除', { type: 'warning' })
    const ids = selectedRows.value.map(r => r.id)
    await deleteOrders(ids)
    ElMessage.success(`已删除 ${selectedRows.value.length} 个订单`)
    selectedRows.value = []
    load()
  }catch{}
}

function onSizeChange(val:number){ size.value = val; current.value = 1; load() }
function onCurrentChange(val:number){ current.value = val; load() }

onMounted(load)
</script>

<template>
  <div class="orders-page">
    <el-card>
      <template #header>
        <div class="hd">我的订单</div>
      </template>

      <!-- 工具栏：筛选、搜索 -->
      <div class="toolbar">
        <div class="left">
          <el-segmented v-model="status" :options="statusOptions" @change="()=>{ current.value=1; load() }" />
        </div>
        <div class="right">
          <div class="batch-ops" v-if="selectedRows.length">
            <span class="selected-count">已选择 {{ selectedRows.length }} 项</span>
            <el-button type="success" size="small" @click="batchPay">批量支付</el-button>
            <el-button type="warning" size="small" @click="batchCancel">批量取消</el-button>
            <el-button type="danger" size="small" @click="batchDelete">批量删除</el-button>
          </div>
          <el-input v-model="keyword" placeholder="按订单号搜索" clearable style="width: 220px" @keyup.enter.native="()=>{ current.value=1; load() }" />
          <el-button type="primary" style="margin-left:8px" @click="()=>{ current.value=1; load() }">查询</el-button>
        </div>
      </div>

      <el-skeleton :loading="loading" :rows="6" animated>
        <template #default>
          <el-table :data="list" border stripe @expand-change="onRowExpand" @selection-change="onSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column type="expand">
              <template #default="{ row }">
                <div class="detail-box">
                  <el-skeleton :loading="detailsMap[String(row.id)]?.loading" :rows="4" animated>
                    <template #default>
                      <el-table :data="detailsMap[String(row.id)]?.items || []" size="small">
                        <el-table-column label="商品" min-width="340">
                          <template #default="{ row: it }">
                            <div class="og-row">
                              <img :src="it.good?.imgs" class="thumb" />
                              <div class="meta">
                                <div class="name">{{ it.good?.name || ('#'+it.goodId) }}</div>
                                <div class="desc elli">{{ it.good?.description }}</div>
                              </div>
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column label="数量" width="120" align="center" prop="count" />
                        <el-table-column label="单价" width="120" align="center">
                          <template #default="{ row: it }">￥{{ it.good?.saleMoney ?? '-' }}</template>
                        </el-table-column>
                        <el-table-column label="小计" width="140" align="center">
                          <template #default="{ row: it }">￥{{ (Number(it.good?.saleMoney||0) * Number(it.count||0)).toFixed(2) }}</template>
                        </el-table-column>
                      </el-table>
                    </template>
                  </el-skeleton>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="订单号" prop="orderNo" min-width="180" />
            <el-table-column label="金额" prop="totalPrice" width="120" />
            <el-table-column label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="row.state==='PAID' ? 'success' : row.state==='CANCELLED' ? 'info' : 'warning'">{{ formatStatus(row.state) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="收货人" prop="linkUser" width="140" />
            <el-table-column label="联系电话" prop="linkPhone" width="160" />
            <el-table-column label="地址" prop="linkAddress" min-width="260" />
            <el-table-column label="下单时间" prop="createTime" min-width="180" />
            <el-table-column label="操作" width="240" fixed="right">
              <template #default="{ row }">
                <el-button text type="primary" @click="(e:any)=> onRowExpand(row, true)">详情</el-button>
                <el-button v-if="row.state==='CREATED'" text type="success" @click="handlePay(row)">支付</el-button>
                <el-button v-if="row.state==='CREATED'" text type="warning" @click="handleCancel(row)">取消</el-button>
                <el-button text type="danger" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pager">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              :page-size="size"
              :current-page="current"
              @size-change="onSizeChange"
              @current-change="onCurrentChange"
            />
          </div>
          <el-empty v-if="!list.length" description="暂无订单" />
        </template>
      </el-skeleton>
    </el-card>
  </div>
</template>

<style scoped>
.orders-page{ width: 97.5%; margin: 16px auto; }
.hd{ font-weight: 700; }
.toolbar{ display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.batch-ops{ display: flex; align-items: center; gap: 8px; margin-right: 16px; }
.selected-count{ color: #606266; font-size: 14px; }
</style>


